﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Utility;
using System.Data;

namespace RoadFlow.Mvc.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class MailController : Controller
    {
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public IActionResult SendMail()
        {
            string opation = Request.Querys("opation");
            Business.Mail mail = new Business.Mail();
            Model.MailOutBox mailOutBox = null;
            string contents = string.Empty;
            string files = string.Empty;
            string receiveUsers = string.Empty;
            string subject = string.Empty;
            string subjectColor = string.Empty;
            bool isRedirect = opation.Equals("redirect");//是否是转发
            bool isReturn = opation.Equals("return");//是否是回复
            bool isAgainEdit = opation.Equals("againedit");//是否再次编辑（从已发送连接过来）
            if (isRedirect || isReturn || isAgainEdit)//转发
            {
                string mailId = Request.Querys("mailid");
                if (mailId.IsGuid(out Guid guid))
                {
                    if (isAgainEdit)
                    {
                        mailOutBox = mail.GetMailOutBox(guid);
                    }
                    else
                    {
                        Model.MailInBox mailInBox = mail.GetMailInBox(guid);
                        if (null != mailInBox)
                        {
                            mailOutBox = mail.GetMailOutBox(mailInBox.OutBoxId);
                            if (null != mailOutBox)
                            {
                                mailOutBox.ReceiveUsers = isRedirect ? "" : "u_" + mailInBox.SendUserId.ToString();
                                mailOutBox.SubjectColor = string.Empty;
                                mailOutBox.Subject = (isRedirect ? "转发" : isReturn ? "回复" : "") + "：" + mailInBox.Subject;
                            }
                        }
                    }
                }
            }
            else
            {
                string id = Request.Querys("id");
                if (id.IsGuid(out Guid guid))
                {
                    mailOutBox = mail.GetMailOutBox(guid);
                }
            }
            
            if(null != mailOutBox)
            {
                receiveUsers = mailOutBox.ReceiveUsers;
                subject = mailOutBox.Subject;
                subjectColor = mailOutBox.SubjectColor;
                Model.MailContent mailContent = mail.GetMailContent(mailOutBox.ContentsId);
                if (null != mailContent)
                {
                    if (isRedirect || isReturn)
                    {
                        contents = "<p></p><p>------------------原始邮件------------------</p><p>发件人："
                            + new Business.User().GetName(mailOutBox.UserId) + "("
                            + new Business.User().GetOrganizeMainShowHtml(mailOutBox.UserId, false) + ")" + "&nbsp;&nbsp;收件时间："
                            + mailOutBox.SendDateTime.ToShortDateTimeString() + "</p>" + mailContent.Contents;
                    }
                    else
                    {
                        contents = mailContent.Contents;
                    }
                    files = mailContent.Files;
                }
            }
            ViewData["contents"] = contents;
            ViewData["files"] = files;
            ViewData["receiveUsers"] = receiveUsers;
            ViewData["subject"] = subject;
            ViewData["subjectColor"] = subjectColor;
            ViewData["refreshtabid"] = Request.Querys("refreshtabid");
            ViewData["query"] = "appid=" + Request.Querys("appid") + "&rf_appopenmodel=" + Request.Querys("rf_appopenmodel") + "&tabid=" + Request.Querys("tabid");
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        /// <summary>
        /// 查看邮件
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public IActionResult ShowMail()
        {
            string mailId = Request.Querys("mailid");
            Model.MailInBox mailInBox = null;
            Business.Mail mail = new Business.Mail();
            if (mailId.IsGuid(out Guid guid))
            {
                mailInBox = mail.GetMailInBox(guid);
            }
            if (mailInBox == null)
            {
                return new ContentResult() { Content = "未找到该邮件!" };
            }
            if (mailInBox.IsRead == 0)//标记为已读
            {
                mail.UpdateIsRead(mailInBox.Id, 1, true);
            }
            string contents = string.Empty;
            string files = string.Empty;
            Model.MailContent mailContent = mail.GetMailContent(mailInBox.ContentsId);
            if (mailContent != null)
            {
                contents = mailContent.Contents;
                files = mailContent.Files.ToFilesShowString(false);
            }
            ViewData["contents"] = contents;
            ViewData["files"] = files;
            ViewData["mailid"] = mailInBox.Id;
            ViewData["query"] = "appid=" + Request.Querys("appid") + "&rf_appopenmodel=" + Request.Querys("rf_appopenmodel")
                + "&tabid=" + Request.Querys("tabid") + "&pagesize=" + Request.Querys("pagesize")
                + "&pagenumber=" + Request.Querys("pagenumber");
            return View(mailInBox);
        }

        /// <summary>
        /// 保存发送邮件
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string SaveSendMail()
        {
            string ReceiveUsers = Request.Forms("ReceiveUsers");
            string Subject = Request.Forms("Subject");
            string SubjectColor = Request.Forms("SubjectColor");
            string Contents = Request.Forms("Contents");
            string Files = Request.Forms("Files");
            string id = Request.Querys("id");
            int Status = Request.Forms("Status").ToInt(0);
            if (Subject.IsNullOrWhiteSpace() || Contents.IsNullOrWhiteSpace() || (Status == 1 && ReceiveUsers.IsNullOrWhiteSpace()))
            {
                return "{\"success\":0,\"message\":\"数据验证错误!\"}";
            }
            Business.Mail mail = new Business.Mail();
            Model.MailOutBox mailOutBox = null;
            Model.MailContent mailContent = null;
            bool isAdd = false;
            if (id.IsGuid(out Guid guid))
            {
                mailOutBox = mail.GetMailOutBox(guid);
            }
            if (null == mailOutBox)
            {
                isAdd = true;
                mailOutBox = new Model.MailOutBox
                {
                    Id = Guid.NewGuid(),
                    ContentsId = Guid.NewGuid()
                };
            }
            mailContent = new Model.MailContent
            {
                Id = mailOutBox.ContentsId
            };
            mailContent.Contents = Contents;
            mailContent.Files = Files;
            mailOutBox.ReceiveUsers = ReceiveUsers;
            mailOutBox.SendDateTime = DateExtensions.Now;
            mailOutBox.Status = Status;
            mailOutBox.Subject = Subject.Trim();
            if (!SubjectColor.IsNullOrWhiteSpace())
            {
                mailOutBox.SubjectColor = SubjectColor;
            }
            mailOutBox.UserId = Current.UserId;
            int i = mail.Send(mailOutBox, mailContent, isAdd);
            return "{\"success\":1,\"message\":\"" + (0 == Status ? "保存" : "发送") + "成功!\",\"id\":\"" + (0 == Status ? mailOutBox.Id.ToString() : "") + "\"}";
        }

        /// <summary>
        /// 标记为已读
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string ChangeStatus()
        {
            Business.Mail mail = new Business.Mail();
            string ids = Request.Forms("ids");
            foreach (string id in ids.Split(','))
            {
                if (!id.IsGuid(out Guid guid))
                {
                    continue;
                }
                var mailInBox = mail.GetMailInBox(guid);
                if (null == mailInBox || mailInBox.IsRead == 1)
                {
                    continue;
                }
                mail.UpdateIsRead(guid, 1, true);
            }
            return "标记成功!";
        }

        /// <summary>
        /// 删除邮件
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string DeleteMail()
        {
            string mailId = Request.Forms("mailid");
            if (!mailId.IsGuid(out Guid guid))
            {
                return "邮件Id错误!";
            }
            int status = Request.Forms("status").ToInt(0);
            Business.Mail mail = new Business.Mail();
            mail.DeleteMailInBox(guid, status);
            return (1 == status ? "彻底" : "") + "删除成功!";
        }

        /// <summary>
        /// 删除邮件（批量）
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string DeleteMail1()
        {
            Business.Mail mail = new Business.Mail();
            string ids = Request.Forms("ids");
            foreach (string id in ids.Split(','))
            {
                if (!id.IsGuid(out Guid guid))
                {
                    continue;
                }
                mail.DeleteMailInBox(guid, 0);
            }
            return "删除成功!";
        }

        /// <summary>
        /// 收件箱
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public IActionResult InBox()
        {
            ViewData["appId"] = Request.Querys("appid");
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["query"] = "appid=" + Request.Querys("appid") + "&rf_appopenmodel=" + Request.Querys("rf_appopenmodel");
            return View();
        }

        /// <summary>
        /// 查询收件箱
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string QueryInBox()
        {
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            string Subject = Request.Forms("Subject");
            string SendUser = Request.Forms("SendUser");
            string Date1 = Request.Forms("Date1");
            string Date2 = Request.Forms("Date2");

            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            string order = (sidx.IsNullOrEmpty() ? "SendDateTime" : sidx) + " " + (sord.IsNullOrEmpty() ? "DESC" : sord);

            var inBoxs = new Business.Mail().GetMailInBoxPagerList(out int count, size, number, Current.UserId, Subject, SendUser.IsNullOrWhiteSpace() ? "" : SendUser.RemoveUserRelationPrefix(), Date1, Date2, order);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.User user = new Business.User();
            Business.Organize organize = new Business.Organize();
            foreach (DataRow dr in inBoxs.Rows)
            {
                //string opation = "<a href='javascript:void(0);' class='list' onclick=\"detail('" + dr["Id"].ToString() + "');\"><i class='fa fa-search'></i>查看</a>";
                System.Text.StringBuilder subject = new System.Text.StringBuilder();
                subject.Append("<a href=\"javascript:;\" class=\"blue\" onclick=\"detail('"+ dr["Id"].ToString() + "');\">");
                if (dr["SubjectColor"].ToString().IsNullOrWhiteSpace())
                {
                    subject.Append(dr["Subject"].ToString());
                }
                else
                {
                    subject.Append("<span style=\"color:" + dr["SubjectColor"].ToString() + "\">" + dr["Subject"].ToString() + "</span>");
                }
                subject.Append("</a>");
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Subject", subject.ToString() },
                    { "SendDateTime", dr["SendDateTime"].ToString().ToDateTime().ToDateTimeString() },
                    { "SendUserId", user.GetName(dr["SendUserId"].ToString().ToGuid())
                        +"<span style=\"color:#666;margin-left:5px;\">("+user.GetOrganizeMainShowHtml(dr["SendUserId"].ToString().ToGuid(), false)+")</span>" },
                    { "IsRead", dr["IsRead"].ToString().Equals("0") ? "<span class=\"noread\">未读</span>" : "<span class=\"read\">已读</span>" }
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        /// <summary>
        /// 草稿箱
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public IActionResult DraftBox()
        {
            ViewData["appId"] = Request.Querys("appid");
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["query"] = "appid=" + Request.Querys("appid") + "&rf_appopenmodel=" + Request.Querys("rf_appopenmodel");
            return View();
        }

        /// <summary>
        /// 查询草稿箱
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string QueryDraftBox()
        {
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            string Subject = Request.Forms("Subject");
            string Date1 = Request.Forms("Date1");
            string Date2 = Request.Forms("Date2");

            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            string order = (sidx.IsNullOrEmpty() ? "SendDateTime" : sidx) + " " + (sord.IsNullOrEmpty() ? "DESC" : sord);

            var outBoxs = new Business.Mail().GetMailOutBoxPagerList(out int count, size, number, Current.UserId, Subject, Date1, Date2, order, 0);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.User user = new Business.User();
            Business.Organize organize = new Business.Organize();
            foreach (DataRow dr in outBoxs.Rows)
            {
                //string opation = "<a href='javascript:void(0);' class='list' onclick=\"detail('" + dr["Id"].ToString() + "');\"><i class='fa fa-pencil-square'></i>编辑</a>";
                System.Text.StringBuilder subject = new System.Text.StringBuilder();
                subject.Append("<a href=\"javascript:;\" class=\"blue\" onclick=\"detail('" + dr["Id"].ToString() + "');\">");
                if (dr["SubjectColor"].ToString().IsNullOrWhiteSpace())
                {
                    subject.Append(dr["Subject"].ToString());
                }
                else
                {
                    subject.Append("<span style=\"color:" + dr["SubjectColor"].ToString() + "\">" + dr["Subject"].ToString() + "</span>");
                }
                subject.Append("</a>");
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Subject", subject.ToString() },
                    { "SendDateTime", dr["SendDateTime"].ToString().ToDateTime().ToDateTimeString() }
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        /// <summary>
        /// 删除草稿邮件
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string DeleteDraftMail()
        {
            Business.Mail mail = new Business.Mail();
            string ids = Request.Forms("ids");
            foreach (string id in ids.Split(','))
            {
                if (!id.IsGuid(out Guid guid))
                {
                    continue;
                }
                mail.DeleteMailOutBox(guid);
            }
            return "删除成功!";
        }

        /// <summary>
        /// 发件箱
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public IActionResult OutBox()
        {
            ViewData["appId"] = Request.Querys("appid");
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["query"] = "appid=" + Request.Querys("appid") + "&rf_appopenmodel=" + Request.Querys("rf_appopenmodel");
            return View();
        }

        /// <summary>
        /// 查询发件箱
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string QueryOutBox()
        {
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            string Subject = Request.Forms("Subject");
            string Date1 = Request.Forms("Date1");
            string Date2 = Request.Forms("Date2");

            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            string order = (sidx.IsNullOrEmpty() ? "SendDateTime" : sidx) + " " + (sord.IsNullOrEmpty() ? "DESC" : sord);

            var outBoxs = new Business.Mail().GetMailOutBoxPagerList(out int count, size, number, Current.UserId, Subject, Date1, Date2, order, 1);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.User user = new Business.User();
            Business.Organize organize = new Business.Organize();
            foreach (DataRow dr in outBoxs.Rows)
            {
                //string opation = "<a href='javascript:void(0);' class='list' onclick=\"detail('" + dr["Id"].ToString() + "');\"><i class='fa fa-pencil-square'></i>编辑</a>";
                System.Text.StringBuilder subject = new System.Text.StringBuilder();
                subject.Append("<a href=\"javascript:;\" class=\"blue\" onclick=\"detail('" + dr["Id"].ToString() + "');\">");
                if (dr["SubjectColor"].ToString().IsNullOrWhiteSpace())
                {
                    subject.Append(dr["Subject"].ToString());
                }
                else
                {
                    subject.Append("<span style=\"color:" + dr["SubjectColor"].ToString() + "\">" + dr["Subject"].ToString() + "</span>");
                }
                subject.Append("</a>");
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Subject", subject.ToString() },
                    { "SendDateTime", dr["SendDateTime"].ToString().ToDateTime().ToDateTimeString() }
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        /// <summary>
        /// 删除发件箱
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string DeleteOutMail()
        {
            Business.Mail mail = new Business.Mail();
            string ids = Request.Forms("ids");
            foreach (string id in ids.Split(','))
            {
                if (!id.IsGuid(out Guid guid))
                {
                    continue;
                }
                mail.DeleteMailOutBox(guid);
            }
            return "删除成功!";
        }

        /// <summary>
        /// 查看已发送邮件
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public IActionResult ShowOutMail()
        {
            string mailId = Request.Querys("mailid");
            Model.MailOutBox mailOutBox = null;
            Business.Mail mail = new Business.Mail();
            if (mailId.IsGuid(out Guid guid))
            {
                mailOutBox = mail.GetMailOutBox(guid);
            }
            if (mailOutBox == null)
            {
                return new ContentResult() { Content = "未找到该邮件!" };
            }
            string contents = string.Empty;
            string files = string.Empty;
            Model.MailContent mailContent = mail.GetMailContent(mailOutBox.ContentsId);
            if (mailContent != null)
            {
                contents = mailContent.Contents;
                files = mailContent.Files.ToFilesShowString(false);
            }
            ViewData["contents"] = contents;
            ViewData["files"] = files;
            ViewData["mailid"] = mailOutBox.Id;
            ViewData["query"] = "appid=" + Request.Querys("appid");
            ViewData["query1"] = "appid=" + Request.Querys("appid") + "&rf_appopenmodel=" + Request.Querys("rf_appopenmodel") +
                "&pagesize=" + Request.Querys("pagesize") + "&pagenumber=" + Request.Querys("pagenumber");
            ViewData["refreshtabid"] = Request.Querys("refreshtabid");
            ViewData["isWithdraw"] = mail.IsWithdraw(guid);
            return View(mailOutBox);
        }

        /// <summary>
        /// 撤回邮件
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string WithdrawOutMail()
        {
            string id = Request.Forms("id");
            if (!id.IsGuid(out Guid guid))
            {
                return "邮件ID错误!";
            }
            if (new Business.Mail().Withdraw(guid))
            {
                return "邮件已成功撤回至草稿箱!";
            }
            else
            {
                return "撤回失败!";
            }
        }

        /// <summary>
        /// 已删除
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public IActionResult DeletedBox()
        {
            ViewData["appId"] = Request.Querys("appid");
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["query"] = "appid=" + Request.Querys("appid") + "&rf_appopenmodel=" + Request.Querys("rf_appopenmodel");
            return View();
        }

        /// <summary>
        /// 查询已删除
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string QueryDeletedBox()
        {
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            string Subject = Request.Forms("Subject");
            string SendUser = Request.Forms("SendUser");
            string Date1 = Request.Forms("Date1");
            string Date2 = Request.Forms("Date2");

            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            string order = (sidx.IsNullOrEmpty() ? "SendDateTime" : sidx) + " " + (sord.IsNullOrEmpty() ? "DESC" : sord);

            var inBoxs = new Business.Mail().GetMailDeletedBoxPagerList(out int count, size, number, Current.UserId, Subject, SendUser.IsNullOrWhiteSpace() ? "" : SendUser.RemoveUserRelationPrefix(), Date1, Date2, order);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.User user = new Business.User();
            Business.Organize organize = new Business.Organize();
            foreach (DataRow dr in inBoxs.Rows)
            {
                //string opation = "<a href='javascript:void(0);' class='list' onclick=\"detail('" + dr["Id"].ToString() + "');\"><i class='fa fa-search'></i>查看</a>";
                System.Text.StringBuilder subject = new System.Text.StringBuilder();
                //subject.Append("<a href=\"javascript:;\" class=\"blue\" onclick=\"detail('" + dr["Id"].ToString() + "');\">");
                if (dr["SubjectColor"].ToString().IsNullOrWhiteSpace())
                {
                    subject.Append(dr["Subject"].ToString());
                }
                else
                {
                    subject.Append("<span style=\"color:" + dr["SubjectColor"].ToString() + "\">" + dr["Subject"].ToString() + "</span>");
                }
                //subject.Append("</a>");
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Subject", subject.ToString() },
                    { "SendUserId", user.GetName(dr["SendUserId"].ToString().ToGuid())
                        +"<span style=\"color:#666;margin-left:5px;\">("+user.GetOrganizeMainShowHtml(dr["SendUserId"].ToString().ToGuid(), false)+")</span>" },
                    { "SendDateTime", dr["SendDateTime"].ToString().ToDateTime().ToDateTimeString() }                   
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        /// <summary>
        /// 还原已删除邮件
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string Recovery()
        {
            string ids = Request.Forms("ids");
            Business.Mail mail = new Business.Mail();
            foreach (string id in ids.Split(','))
            {
                if (!id.IsGuid(out Guid guid))
                {
                    continue;
                }
                mail.RecoveryMailDeletedBox(guid);
            }
            return "邮件已成功还原至收件箱!";
        }

        /// <summary>
        /// 删除已删除邮件
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string DeleteDeletedMail()
        {
            Business.Mail mail = new Business.Mail();
            string ids = Request.Forms("ids");
            foreach (string id in ids.Split(','))
            {
                if (!id.IsGuid(out Guid guid))
                {
                    continue;
                }
                var deleteMail = mail.GetMailDeletedBox(guid);
                if (null == deleteMail)
                {
                    continue;
                }
                mail.DeleteMailDeletedBox(deleteMail);
            }
            return "删除成功!";
        }
    }
}